package com.atguigu.edu2021.mock.stage;

import com.atguigu.edu2021.mock.bean.*;
import com.atguigu.edu2021.mock.config.AppConfig;
import com.atguigu.edu2021.mock.factory.UserSession;
import com.atguigu.edu2021.mock.log.*;
import com.atguigu.edu2021.mock.log.enums.ActionId;
import com.atguigu.edu2021.mock.log.enums.ItemType;
import com.atguigu.edu2021.mock.log.enums.PageId;
import com.atguigu.edu2021.mock.service.CommentInfoService;
import com.atguigu.edu2021.mock.service.CourseInfoService;
import com.atguigu.edu2021.mock.service.ReviewInfoService;
import com.atguigu.edu2021.mock.service.UserChapterProcessService;
import com.atguigu.mock.util.LogUtil;
import com.atguigu.mock.util.RandomBox;
import com.atguigu.mock.util.RandomCollection;
import com.atguigu.mock.util.RandomNum;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component("chapterVideo")
@Slf4j
public class ChapterVideoStage implements  Stage {

    @Autowired
    UserChapterProcessService userChapterProcessService;

    @Autowired
    ReviewInfoService reviewInfoService;


    @Autowired
    CommentInfoService commentInfoService;

    @Autowired
    CourseInfoService courseInfoService;


    @Override
    public boolean handle() {
        ChapterInfo chapterInfo = getChapterInfo();

        AppMain appMain = mainLog(chapterInfo);
        //添加视频浏览情况
        List<AppMain> videoLogList = videoHeartBeat(appMain, chapterInfo);
        LogUtil.logToJson(appMain);
        for (AppMain videoLog : videoLogList) {
            LogUtil.logToJson(videoLog);
        }
        LogUtil.logToJson(appMain);

        //保存用户播放进度
        saveUserChapterProcess( videoLogList,  chapterInfo);
        //
        handleReview(  appMain,   UserSession.getCurCourseInfo() );
        handleComment(  appMain,   chapterInfo );
        UserSession.setLastPageId(PageId.chapter_video);
       // UserSession.addTimeByDuringTime(appMain.getPage().getDuring_time());
        return true;
    }

    private  ChapterInfo  getChapterInfo(){
        CourseInfo curCourseInfo = UserSession.getCurCourseInfo();
        List<ChapterInfo> chapterInfoList = curCourseInfo.getChapterInfoList();
        ChapterInfo chapterInfo = RandomCollection.getOneFrom(chapterInfoList);
        return  chapterInfo;

    }

    private  List<AppMain>  videoHeartBeat(AppMain appMain,ChapterInfo chapterInfo  ){
        Integer videoHeartIntervalSec = AppConfig.video_heart_interval_sec;
        Integer playSecThrehold = (appMain.getPage().getDuring_time()-5000)/1000;
        List<AppMain> videoLogList=new ArrayList();

        Integer totalplaySec=videoHeartIntervalSec;
        while (true ) {
            int pauseNum = RandomNum.getRandInt(1, AppConfig.video_heart_interval_sec * 10); // 随机 产生  间隔10倍以内的数 10%几率小于间隔，则该数为暂停数
            if (totalplaySec < playSecThrehold){
                Integer thisIntervalPlaySec= AppConfig.video_heart_interval_sec;
                if(pauseNum< AppConfig.video_heart_interval_sec){  //10%触发 暂停
                    thisIntervalPlaySec=thisIntervalPlaySec- pauseNum;
                }
                UserSession.addTimeByDuringTime(thisIntervalPlaySec*1000);

                AppVideo appVideo = AppVideo.builder().play_sec(thisIntervalPlaySec)
                        .video_id(chapterInfo.getVideoId().toString())
                        .position_sec(totalplaySec).build();
                AppMain appMainV = AppMain.builder().common(appMain.getCommon()).appVideo(appVideo).ts(UserSession.getCurDateTime().getTime()).checkError().build();
                videoLogList.add(appMainV);
                totalplaySec+=videoHeartIntervalSec;
           } else  {
                Integer thisIntervalPlaySec=  totalplaySec - playSecThrehold ;

                AppVideo appVideo = AppVideo.builder().play_sec(thisIntervalPlaySec)
                        .video_id(chapterInfo.getVideoId().toString())
                        .position_sec(totalplaySec).build();
                UserSession.addTimeByDuringTime(thisIntervalPlaySec*1000);
                AppMain appMainV = AppMain.builder().common(appMain.getCommon()).appVideo(appVideo).ts(UserSession.getCurDateTime().getTime()).checkError().build();
                videoLogList.add(appMainV);
                break;
            }

        }
        return  videoLogList;

    }



    private AppMain mainLog(ChapterInfo chapterInfo){
        AppCommon appCommon = UserSession.getAppCommon();

        Integer durTime= RandomNum.getRandInt(5000,   chapterInfo.getVideoInfo().getDuringSec()*1000);

        AppPage appPage = AppPage.builder()
                .last_page_id(UserSession.getLastPageId())
                .item( chapterInfo.getId()+"")
                 .extend1(chapterInfo.getVideoId().toString())
                .item_type(ItemType.chapter_id)
                .during_time(durTime)
                .page_id(PageId.chapter_video).build();

        List<AppDisplay> appDisplayList = AppDisplay.builder().buildList();
        UserSession.addTimeByDuringTime(durTime);

        AppMain appMain = AppMain.builder().common(appCommon).page(appPage).displays(appDisplayList).ts(UserSession.getCurDateTime().getTime() ).build();
        return appMain;
    }

    private   void   saveUserChapterProcess(List<AppMain> appMainList,ChapterInfo chapterInfo){

        Integer totalPlaySec=0;
        for (AppMain appMain : appMainList) {
            totalPlaySec+=appMain.getAppVideo().getPlay_sec();
        }
            UserChapterProcess userChapterProcess = new UserChapterProcess();
            userChapterProcess.setChapterId(chapterInfo.getId());
            userChapterProcess.setCourseId(chapterInfo.getCourseId());
            userChapterProcess.setPositionSec(totalPlaySec);
            userChapterProcess.setCreateTime(UserSession.getCurDateTime());
            userChapterProcess.setUserId(UserSession.getUserInfo().getId());
            userChapterProcess.setDeleted("0");
        userChapterProcessService.remove(new QueryWrapper<UserChapterProcess>()
                .eq("user_id",UserSession.getUserInfo().getId())
                .eq("chapter_id",chapterInfo.getId() ));
           userChapterProcessService.saveOrUpdate(userChapterProcess) ;


    }

    // 评价
    private  void   handleReview(AppMain appMain, CourseInfo courseInfo ){


        if(UserSession.isStudy()){
            ReviewInfo existsReviewInfo  = reviewInfoService.getOne(new QueryWrapper<ReviewInfo>().eq("user_id", UserSession.getUserInfo().getId()).eq("course_id", courseInfo.getId()));
            log.debug( ""+existsReviewInfo);
            if(existsReviewInfo==null){
                ReviewInfo reviewInfo = initReviewInfo(courseInfo);
                reviewInfoService.saveOrUpdate(reviewInfo);

                AppAction reviewAction = new AppAction(ActionId.review_add, ItemType.course_id, courseInfo.getId().toString(),UserSession.getCurDateTime().getTime() );
                appMain.addAction(reviewAction);

            }

        }

    }


    public ReviewInfo initReviewInfo(CourseInfo courseInfo){

        ReviewInfo reviewInfo = new ReviewInfo();
        reviewInfo.setCourseId(courseInfo.getId());
        reviewInfo.setCreateTime(UserSession.getCurDateTime());
        Integer[] appraise_weight = AppConfig.appraise_weight;
        RandomBox<Integer> appraiseBox = RandomBox.builder().add(5, appraise_weight[0])
                .add(4, appraise_weight[1])
                .add(3, appraise_weight[2])
                .add(2, appraise_weight[3])
                .add(1, appraise_weight[4]).build();


        Integer appraise = appraiseBox.getValue();

        reviewInfo.setReviewStars(appraise);
        reviewInfo.setCourseId(courseInfo.getId());
        reviewInfo.setUserId(UserSession.getUserInfo().getId());
        reviewInfo.setUserId(UserSession.getUserInfo().getId());

        reviewInfo.setCreateTime(UserSession.getCurDateTime());
        reviewInfo.setDeleted("0");
        return reviewInfo;

    }



    // 评论
    private  void   handleComment(AppMain appMain,  ChapterInfo chapterInfo ){


        if(UserSession.isStudy()){
            CommentInfo CommentInfo = initCommentInfo(chapterInfo);
            commentInfoService.saveOrUpdate(CommentInfo);

            AppAction commentAction = new AppAction(ActionId.comment_add, ItemType.chapter_id, chapterInfo.getId().toString(),UserSession.getCurDateTime().getTime());
            appMain.addAction(commentAction);

       }



    }


    public CommentInfo initCommentInfo(ChapterInfo chapterInfo){

        CommentInfo commentInfo = new CommentInfo();
        commentInfo.setCommentTxt("评论 123123"   );
        commentInfo.setChapterId(chapterInfo.getId());
        commentInfo.setCourseId(chapterInfo.getCourseId());
        commentInfo.setUserId(UserSession.getUserInfo().getId());


        commentInfo.setCreateTime(UserSession.getCurDateTime());
        commentInfo.setDeleted("0");
        return commentInfo;

    }
}
